import axios from 'axios'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api'

// 创建 axios 实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error.response?.data?.message || '请求失败')
  }
)

// 认证相关 API
export const authApi = {
  login: (credentials: { username: string; password: string }) =>
    api.post('/auth/login', credentials),

  register: (userData: {
    username: string
    password: string
    email?: string
    phone?: string
    nickname?: string
  }) => api.post('/auth/register', userData),

  logout: () => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  },

  getCurrentUser: () => api.get('/users/profile'),
}

// 用户相关 API
export const userApi = {
  getProfile: () => api.get('/users/profile'),
  updateProfile: (data: any) => api.put('/users/profile', data),
  changePassword: (data: { currentPassword: string; newPassword: string }) =>
    api.put('/users/password', data),
  uploadAvatar: (file: File) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return api.post('/users/avatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
  },
}

// 家族成员相关 API
export const familyApi = {
  getMembers: () => api.get('/family/members'),
  getMember: (id: number) => api.get(`/family/members/${id}`),
  createMember: (member: any) => api.post('/family/members', member),
  updateMember: (id: number, member: any) => api.put(`/family/members/${id}`, member),
  deleteMember: (id: number) => api.delete(`/family/members/${id}`),
  getTrees: () => api.get('/family/trees'),
  getTree: (id: number) => api.get(`/family/trees/${id}`),
  createTree: (tree: any) => api.post('/family/trees', tree),
}

// 荣誉相关 API
export const honorApi = {
  getHonors: () => api.get('/honors'),
  getHonor: (id: number) => api.get(`/honors/${id}`),
  createHonor: (honor: any) => api.post('/honors', honor),
  updateHonor: (id: number, honor: any) => api.put(`/honors/${id}`, honor),
  deleteHonor: (id: number) => api.delete(`/honors/${id}`),
}

// 族规模板相关 API
export const clanApi = {
  getTemplates: () => api.get('/clan/templates'),
  getTemplate: (id: number) => api.get(`/clan/templates/${id}`),
  createTemplate: (template: any) => api.post('/clan/templates', template),
  updateTemplate: (id: number, template: any) => api.put(`/clan/templates/${id}`, template),
  deleteTemplate: (id: number) => api.delete(`/clan/templates/${id}`),
  addComment: (templateId: number, comment: any) =>
    api.post(`/clan/templates/${templateId}/comments`, comment),
}

// AI 相关 API
export const aiApi = {
  chat: (message: string, scenario?: string) =>
    api.post('/ai/chat', { message, scenario }),
  
  generateContent: (type: string, prompt: string) =>
    api.post('/ai/generate', { type, prompt }),

  getConversations: () => api.get('/ai/conversations'),
  continueConversation: (sessionId: string, message: string) =>
    api.post(`/ai/conversations/${sessionId}`, { message }),
}

export default api